var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

var app = express();

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({
    extended: false
}));
app.use(cookieParser('kuaijian'));

//引入并注册session中间件
const session = require('express-session')
app.use(session({
    //cookie数据的加密
    secret: 'kuaijian',
    //cookie的名称
    name: 'sessionID',
    //默认为true,只要保存了session，是否重新处理保存，即使数据没有发生改变
    resave: false,
    //保存在session文件中序列化成字符串保存
    saveUninitialized: true
}))


//静态文件目录
app.use(express.static(path.join(__dirname, 'public')));
//使用art-template模板引擎
app.engine('html', require('express-art-template'))

//注册返回信息的中间件
app.use((req, res, next) => {
    //封装返回数据的函数
    res.cc = function (status = 200, msg = '', data = []) {
        res.json({
            status,
            msg,
            data
        })
    }
    next()
})


//全局中间件，判断是否登录了
 /*  app.use((req, res, next) => {
   //获取访问的路由地址 
   let url =req.baseUrl + req.path
   //除了登录页面不需要做登录验证，后台其他页面都需要做登录验证
   if (url != '/admin/login') {
        //先判断cookie中有没有保留登录信息
        if (!req.signedCookies.isLogin) {
            if (!req.session.isLogin) {
               res.redirect('/admin/login')
            }
        }
    }
    next()
}) */


//简记url地址
app.get('/', (req, res) => {
    res.redirect('/admin/index')
})


//导入路由模块
var loginRouter = require('./routes/login');
var indexRouter = require('./routes/index');
var cateRouter=require('./routes/cate')
var newsRouter=require('./routes/news')
var uploadRouter=require('./routes/upload')
var comRouter=require('./routes/comment')

//注册路由
app.use('/admin', loginRouter);
app.use('/admin', indexRouter);
app.use('/admin', cateRouter);
app.use('/admin', newsRouter);
app.use('/', uploadRouter);
app.use('/admin',comRouter);


const joi = require('joi')

// 注册全局错误级别中间件中，捕获验证失败的错误，并把验证失败的结果响应给客户端
app.use(function (err, req, res, next) {
    // 数据验证失败
    if (err instanceof joi.ValidationError) return res.cc(400,err.message)
    // 未知错误
    res.cc(500,err.message)
})



module.exports = app;